<template>
  <view>
    <uni-forms ref="form">
      <!-- 头像 -->
      <uni-forms-item label="头像" name="avatar" :labelWidth="80" class="display-default frems-item"
        style="margin-bottom: 0px;">
        <view class="frems-item-view">
          <image class="user-avatar"
            :src="tempFilePath || (user.avatar ? $url+user.avatar : '/static/myCenter/defaultAvatar.png')"
            @click="upAvatar">
          </image>
        </view>
      </uni-forms-item>
      <!-- 昵称 -->
      <uni-forms-item label="设置昵称" name="username" :labelWidth="80" class="display-default frems-item"
        style="margin-bottom: 0px;">
        <view class="frems-item-view">
          <input class="frems-item-right-value" type="text" v-model="user.username" />
        </view>
      </uni-forms-item>
      <!-- 签名 -->
      <uni-forms-item label="设置签名" name="introduce" :labelWidth="80" class="display-default frems-item"
        style="margin-bottom: 0px;">
        <view class="frems-item-view">
          <input class="frems-item-right-value" type="text" v-model="user.introduce" />
        </view>
      </uni-forms-item>
      <!-- 性别，底部弹出选项 -->
      <view @click="popupOpen('sexPopup')">
        <uni-forms-item label="性别" name="sex" :labelWidth="80" class="display-default frems-item frems-item-active"
          style="margin-bottom: 0px;">
          <view class="frems-item-view">
            <text class="frems-item-right-value" v-text="user.sex == 0 ? '男' : '女'"></text>
          </view>
        </uni-forms-item>
      </view>
      <!-- 生日，使用uni-datetime-picker选择日期 -->
      <view>
        <uni-forms-item label="生日" name="birthday" :labelWidth="80" class="display-default frems-item frems-item-active"
          style="margin-bottom: 0px;">
          <view class="frems-item-view">
            <uni-datetime-picker ref="datetime" class="frems-item-right-value" type="date" v-model="user.birthday"
              :clearIcon="false">
              {{user.birthday || '选择出生日期'}}
            </uni-datetime-picker>
          </view>
        </uni-forms-item>
      </view>
      <!-- 邮箱 -->
      <!--  <uni-forms-item label="邮箱" name="email" :labelWidth="80" class="display-default frems-item"
        style="margin-bottom: 0px;">
        <view class="frems-item-view">
          <input class="frems-item-right-value" type="text" v-model="user.email" />
        </view>
      </uni-forms-item> -->
      <!-- QQ号 -->
      <uni-forms-item label="QQ号" name="qqNumber" :labelWidth="80" class="display-default frems-item"
        style="margin-bottom: 0px;">
        <view class="frems-item-view">
          <input class="frems-item-right-value" type="number" placeholder="QQ号" v-model="user.qqNumber"
            :maxlength="11" />
        </view>
      </uni-forms-item>
      <!-- 微信号 -->
      <uni-forms-item label="微信号" name="wxNumber" :labelWidth="80" class="display-default frems-item"
        style="margin-bottom: 0px;">
        <view class="frems-item-view">
          <input class="frems-item-right-value" type="text" placeholder="微信号" v-model="user.wxNumber" :maxlength="24" />
        </view>
      </uni-forms-item>
      <!-- 院系，底部弹出选项 -->
      <view @click="popupOpen('departmentPopup')">
        <uni-forms-item label="院系" name="department" :labelWidth="80"
          class="display-default frems-item frems-item-active" style="margin-bottom: 0px;">
          <view class="frems-item-view">
            <text class="frems-item-right-value">{{user.department || '选择院系'}}</text>
          </view>
        </uni-forms-item>
      </view>
    </uni-forms>

    <!-- 性别选项弹出层 -->
    <uni-popup ref="sexPopup" type="bottom">
      <view class="sexDialog-popup-body">
        <view class="display-default select-sex-item" :style="user.sex == 0 ? '' : 'color:#6d6d6d'"
          @click="sexSelect(0)">
          男 <uni-icons v-show="user.sex == 0" style="position: absolute;right: 70rpx;" custom-prefix="iconfont"
            type="checkmarkempty" size="20"></uni-icons>
        </view>
        <view class="display-default select-sex-item" :style="user.sex == 1 ? '' : 'color:#6d6d6d'"
          @click="sexSelect(1)">
          女<uni-icons v-show="user.sex == 1" style="position: absolute;right: 70rpx;" custom-prefix="iconfont"
            type="checkmarkempty" size="20"></uni-icons>
        </view>
        <button class="sexDialog-button-cancel" @click="popupClose('sexPopup')">取消</button>
      </view>
    </uni-popup>

    <!-- 院系选项弹出层 -->
    <uni-popup ref="departmentPopup" type="bottom">
      <view class="departmentDialog-popup-body">
        <scroll-view :scroll-y="true" style="height: 500rpx;" :scroll-into-view="'tab'+departmentPopupItemId">
          <view :id="'tab'+index" class="display-default select-department-item"
            :style="item.value == user.department ? '' : 'color:#6d6d6d'" @click="departmentSelect(item.value,index)"
            v-for="(item,index) in departmentLocaldata" :key="index">
            <text>{{item.value}}</text>
            <uni-icons v-show="item.value == user.department" style="position: absolute;right: 70rpx;"
              custom-prefix="iconfont" type="checkmarkempty" size="20"></uni-icons>
          </view>
        </scroll-view>

        <button class="departmentDialog-button-cancel" @click="popupClose('departmentPopup')">取消</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        tempFilePath: '',
        departmentPopupItemId: '',
        user: {},
        // department院系数据
        departmentLocaldata: [{
          id: '0',
          value: '电子信息工程学院'
        }, {
          id: '1',
          value: '建筑工程学院'
        }, {
          id: '2',
          value: '文化传播学院'
        }, {
          id: '3',
          value: '农业工程学院'
        }, {
          id: '4',
          value: '机电工程学院'
        }, {
          id: '5',
          value: '汽车学院'
        }, {
          id: '6',
          value: '会计学院'
        }, {
          id: '7',
          value: '艺术设计学院'
        }, {
          id: '8',
          value: '经济管理学院'
        }],
        token: ''
      };
    },
    async onLoad() {
      uni.showLoading({
        title: '正在加载中...',
        mask: false
      });

      // 页面加载时获取 token
      this.token = await uni.getStorageSync('token')

      // 查询用户基本信息
      await this.$http.user.getUserInfoByToken(this.token).then(res => {
        console.log("res: " + JSON.stringify(res));
        this.user = res.data
        // this.user.birthday = res.data.birthday == null ? '请选择出生日期' : res.data.birthday

        // 初始化院系弹出框，当前选择的院系的索引位置
        for (let i = 0; i < this.departmentLocaldata.length; i++) {
          if (this.departmentLocaldata[i].value == this.user.department) {
            this.departmentPopupItemId = i
          }
        }
      }).catch(err => {
        console.log("res: " + JSON.stringify(res));
      })

      uni.hideLoading()
    },
    // 点击右上角保存按钮
    async onNavigationBarButtonTap() {
      if (!this.user.username.trim()) {
        return uni.showToast({
          title: '昵称不能为空',
          icon: 'none',
          position: 'center'
        });
      }

      if (this.user.username.trim().length < 2 || this.user.username.trim().length > 24) {
        return uni.showToast({
          title: '昵称长度在 2 到 24 个字符',
          icon: 'none',
          position: 'center'
        });
      }

      // 显示Loading提示框
      uni.showLoading({
        title: '正在提交...',
        mask: false
      });

      if (this.tempFilePath) {
        // 使用Promise同步操作，先上传图片到服务器，然后再将服务器返回的图片地址保存到数据库中
        await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: this.$url + 'common/upload',
            filePath: this.tempFilePath,
            formData: {
              'type': 'avatarImage'
            },
            name: 'files0',
            header: {
              "Authorization": this.token
            },
            success: (res) => {
              return resolve(res)
            },
            fail: (err) => {
              return reject(err)
            },
          })
        }).then((res) => {
          console.log("res: " + JSON.stringify(res));

          let avatarUrl = JSON.parse(res.data).data.url
          console.log("avatarUrl: " + JSON.stringify(avatarUrl));

          if (avatarUrl) {
            // 上传成功，获取到数据
            this.user.avatar = avatarUrl
          } else {
            // 上传失败，返回失败结果
            uni.showToast({
              title: '上传图片失败，预料外的错误！',
              icon: 'none',
              position: 'center'
            });

            // 跳出方法，不继续执行
            return
          }
        }).catch(err => {
          console.log("err: " + JSON.stringify(err));
          uni.showToast({
            title: '服务器开小差了',
            icon: 'none',
            position: 'center'
          });

          // 跳出方法，不继续执行
          return
        })

        await this.$http.user.editUserInfoByToken(this.token, this.user).then(res => {
          console.log("res: " + JSON.stringify(res));

          if (res.code == 401) {
            uni.showToast({
              title: res.msg,
              icon: 'none',
              position: 'center'
            });
            return
          }
          if (!res.code) {
            uni.showToast({
              title: '服务器开小差了',
              icon: 'none',
              position: 'center'
            });
            return
          }

          uni.showToast({
            title: res.msg,
            icon: 'none',
            position: 'center'
          });

          // 延迟 0.5 秒跳转
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/myCenter/myCenter'
            })
          }, 500)
        }).catch(err => {
          console.log("err: " + JSON.stringify(err));
          uni.showToast({
            title: '服务器开小差了',
            icon: 'none',
            position: 'center'
          });
        })
      } else {
        await this.$http.user.editUserInfoByToken(this.token, this.user).then(res => {
          console.log("res: " + JSON.stringify(res));

          if (res.code == 200) {
            // 延迟 0.5 秒跳转
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/myCenter/myCenter'
              })
            }, 500)
          } else if (!res.code) {
            return uni.showToast({
              title: '服务器开小差了',
              icon: 'none',
              position: 'center'
            });
          }

          uni.showToast({
            title: res.msg,
            icon: 'none',
            position: 'center'
          });
        }).catch(err => {
          console.log("err: " + JSON.stringify(err));
          uni.showToast({
            title: '服务器开小差了',
            icon: 'none',
            position: 'center'
          });
        })
      }

      // 隐藏Loading提示框
      uni.hideLoading()
    },
    methods: {
      // 选择头像
      upAvatar() {
        uni.chooseImage({
          count: 1,
          success: (e) => {
            this.tempFilePath = e.tempFilePaths[0]
            console.log(this.tempFilePath);
          }
        })
      },
      // 打开弹出层
      popupOpen(popupName) {
        if (popupName == 'sexPopup') {
          return this.$refs.sexPopup.open()
        }

        if (popupName == 'departmentPopup') {
          return this.$refs.departmentPopup.open()
        }
      },
      // 选择性别中，点击 [男、女]
      sexSelect(sex) {
        this.user.sex = sex
        this.$refs.sexPopup.close()
      },
      // 收起弹出层
      popupClose(popupName) {
        if (popupName == 'sexPopup') {
          return this.$refs.sexPopup.close()
        }

        if (popupName == 'departmentPopup') {
          return this.$refs.departmentPopup.close()
        }
      },
      // 选择院系中，点击 [.....]]
      departmentSelect(department, index) {
        this.user.department = department
        this.departmentPopupItemId = index

        this.$refs.departmentPopup.close()
      }
    }
  }
</script>

<style lang="scss">
  // frems左侧label字体颜色
  /deep/ .uni-forms-item__label {
    color: #000;
  }

  // App端需要用这种方法，我也不知道为什么
  .frems-item .uni-forms-item__label {
    color: #000;
  }

  .frems-item {
    background: #fff;
    border-top: 1px solid #eee;
    padding: 10rpx 30rpx;

    // frems-item内的view容器
    & .frems-item-view {
      text-align: end;
      display: flex;
      justify-content: flex-end;

      // 上传头像样式
      & .user-avatar {
        width: 130rpx;
        height: 130rpx;
        border-radius: 60px;
        background: #fff;
      }

      & .frems-item-right-value {
        text-align: end;
        font-size: 14px;
        color: #6d6d6d;
      }
    }
  }

  // 点击性别的弹出层选项
  .sexDialog-popup-body,
  .departmentDialog-popup-body {
    padding-bottom: 80rpx;
    border-radius: 10px 10px 0 0;
    background: #fff;

    & .select-sex-item,
    & .select-department-item {
      position: relative;
      font-size: 16px;
      padding: 30rpx;
    }

    & .sexDialog-button-cancel,
    & .departmentDialog-button-cancel {
      background: #eee;
      margin-top: 30rpx;
      padding: 5rpx 0;
      font-size: 16px;
      width: 90%;
    }
  }

  .frems-item-active:active {
    background: #f0f0f0;
  }
</style>
